//
//  HMComposePictureView.swift
//  Weibo
//
//  Created by itteacher on 2017/7/31.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
//  发微博配图
class HMComposePictureView: UICollectionView {
    //  点击加号cell执行 的闭包
    var clickAddClosure: (()->())?
    
    //  数据源
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件
    private func setupUI() {
        //  隐藏配图
        self.isHidden = true
        //  注册cell
        register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: ComposePictureViewCellIdentifier)
       
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
    }
    
    //  添加图片
    func addImage(image: UIImage) {
        
        if images.count >= 9 {
            //  最多显示9张
            return
        }
        
        //  添加图片显示图片
        self.isHidden = false
        images.append(image)
        reloadData()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  每项间距
        let itemMargin: CGFloat = 5
        //  每项的宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        //  设置大小
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  设置最小间距
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
    }

}
//  MARK: --UICollectionViewDataSource
extension HMComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9 {
            return images.count
        }
        //  不是0或者9张需要多加1显示加号
        return images.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComposePictureViewCellIdentifier, for: indexPath) as! HMComposePictureViewCell
        //  如果是加号图片，不能直接数组里面的值
        if indexPath.item == images.count {
            //  加号图片
            cell.image = nil
        } else {
            //  设置数据
            cell.image = images[indexPath.item]
            //  设置indexPath
            cell.currentIndexPath = indexPath
            //  设置删除闭包
            cell.deleteButtonClosure = { [unowned self] (index: Int) in
                //  删除图片
                self.images.remove(at: index)
                //  重写加载
                self.reloadData()
                //  判断是否配图个数为0
                if self.images.count == 0 {
                    //  隐藏
                    self.isHidden = true
                }
            }
        }
       
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item  == images.count {
            //  最后一个cell
            print("左后一个cell 了")
            //  执行闭包
            clickAddClosure?()
        }
    }
}

// 自定义配图cell
class HMComposePictureViewCell: UICollectionViewCell {
    //  cell对应的indexPath
    var currentIndexPath: IndexPath?
    //  删除按钮执行的闭包
    var deleteButtonClosure: ((Int)->())?
    
    //  MARK: --懒加载控件
    fileprivate lazy var imageView: UIImageView = UIImageView()
    //  删除按
    fileprivate lazy var deleteButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()
    
    //  显示数据
    var image: UIImage? {
        didSet {
            if image != nil {
                imageView.image = image
                //  有图片显示删除按钮
                deleteButton.isHidden = false
            } else {
                //  加号图片
                imageView.image = UIImage(named: "compose_pic_add")
                //  没有图片隐藏删除按钮
                deleteButton.isHidden = true
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    //  MARK: --   点击删除按钮的逻辑处理
    @objc private func deleteButtonAction() {
        //  删除操作
        guard let item = currentIndexPath?.item else {
            return
        }
        print(item)
        //  执行删除闭包
        deleteButtonClosure?(item)
        
    }

}


